package cn.stylefeng.guns.modular.pay.controller;

import cn.stylefeng.guns.config.pay.SignConfig;
import cn.stylefeng.guns.modular.account.service.AccountService;
import cn.stylefeng.guns.modular.pay.sign.RSA;
import cn.stylefeng.guns.modular.recharge.model.params.RechargeParam;
import cn.stylefeng.guns.modular.recharge.model.result.RechargeResult;
import cn.stylefeng.guns.modular.recharge.service.RechargeService;
import cn.stylefeng.guns.modular.statistic.entity.DayIncome;
import cn.stylefeng.guns.modular.statistic.entity.DayStatistic;
import cn.stylefeng.guns.modular.statistic.entity.MonthIncome;
import cn.stylefeng.guns.modular.statistic.entity.MonthStatistic;
import cn.stylefeng.guns.modular.statistic.model.result.DayIncomeResult;
import cn.stylefeng.guns.modular.statistic.model.result.DayStatisticResult;
import cn.stylefeng.guns.modular.statistic.model.result.MonthIncomeResult;
import cn.stylefeng.guns.modular.statistic.model.result.MonthStatisticResult;
import cn.stylefeng.guns.modular.statistic.service.DayIncomeService;
import cn.stylefeng.guns.modular.statistic.service.MonthIncomeService;
import cn.stylefeng.roses.core.util.HttpContext;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;

/**
 * @Description: CallbackController
 * @Author liuqiang
 * @Date 2020-02-08 17:28
 */

@RestController
@RequestMapping("callback")
@Slf4j
public class CallbackController {

    @Autowired
    private RechargeService rechargeService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private DayIncomeService dayIncomeService;
    @Autowired
    private MonthIncomeService monthIncomeService;

    @PostMapping("/call")
    public String callback(@RequestBody String context){
        String sign = HttpContext.getRequest().getHeader("sign");
        boolean verify = RSA.verify(context, sign,SignConfig.PAYMAX_PUBLIC_KEY);
        if(verify){
            JSONObject callbackData = JSONObject.parseObject(context);
            String type = callbackData.getString("type");
            JSONObject data = callbackData.getJSONObject("data");
            String orderNo = data.getString("order_no");
            String serialNo = data.getString("id");
            String status = data.getString("status");
            switch (type){
                case "CHARGE"://支付成功
                    if("SUCCEED".equals(status)){
                        RechargeResult recharge = rechargeService.findByOrderNo(orderNo);
                        if(recharge != null){
                            RechargeParam rechargeParam = new RechargeParam();
                            rechargeParam.setId(recharge.getId());
                            rechargeParam.setState(1);
                            rechargeService.update(rechargeParam);

                            //给账号加钱
                            String phone = recharge.getPhone();
                            accountService.addByPhone(phone,recharge.getAmount());

                            //统计
                            statistic(recharge.getAmount());
                        }
                        log.info("支付成功回调：orderNo={},serialNo={}",orderNo,serialNo);
                    }else {
                        log.info("支付失败==orderNo={},serialNo={}",orderNo,serialNo);
                    }
                    break;
                case "REFUND":

                    break;
                default:
                    break;
            }

        }

        return "success";
    }

    private void statistic(BigDecimal amount){
        LocalDate localDate = LocalDate.now();
        //每天统计
        String dateStr = localDate.toString().replaceAll("-", "");
        int day = Integer.parseInt(dateStr);
        DayIncomeResult dayResult = dayIncomeService.findByDay(day);
        if(dayResult == null){
            DayIncome dayIncome = new DayIncome();
            dayIncome.setIncome(amount);
            dayIncome.setDay(day);

            dayIncomeService.save(dayIncome);
        }else{
            BigDecimal income = dayResult.getIncome();
            BigDecimal newIncome = income.add(amount);
            DayIncome dayIncome = new DayIncome();
            dayIncome.setId(dayResult.getId());
            dayIncome.setIncome(newIncome);
            dayIncome.setDay(day);

            dayIncomeService.updateById(dayIncome);
        }

        //月统计
        int month = Integer.parseInt(dateStr.substring(0,6));
        MonthIncomeResult monthResult = monthIncomeService.findByMonth(month);
        if(monthResult == null){
            MonthIncome monthIncome = new MonthIncome();
            monthIncome.setIncome(amount);
            monthIncome.setMonth(month);

            monthIncomeService.save(monthIncome);
        }else {

            BigDecimal income = monthResult.getIncome();
            BigDecimal newIncome = income.add(amount);

            MonthIncome monthIncome = new MonthIncome();
            monthIncome.setId(monthResult.getId());
            monthIncome.setMonth(month);
            monthIncome.setIncome(newIncome);

            monthIncomeService.updateById(monthIncome);
        }

    }
}
